﻿@{
    ViewData["Title"] = "Home Page";
}

<script type="text/javascript">

    const id = '@Guid.NewGuid().ToString()';
    const baseUrl = "api/webrtc/";
    const getOfferUrl = `${baseUrl}getoffer?id=${id}`;
    const setAnswerUrl = `${baseUrl}setanswer?id=${id}`;
    const setIceCandidateUrl = `${baseUrl}addicecandidate?id=${id}`

    var pc

    async function start() {

        closePeer();

        let videoControl = document.querySelector('#audioCtl');

        const localStream = await navigator.mediaDevices.getUserMedia({ video: false, audio: true });
        videoControl.srcObject = localStream;

        pc = new RTCPeerConnection(null);

        localStream.getTracks().forEach(track => {
            console.log('add local track ' + track.kind + ' to peer connection.');
            console.log(track);
            pc.addTrack(track, localStream);
        });

        pc.onicegatheringstatechange = function () {
            console.log("onicegatheringstatechange: " + pc.iceGatheringState);
        }

        pc.oniceconnectionstatechange = function () {
            console.log("oniceconnectionstatechange: " + pc.iceConnectionState);
        }

        pc.onsignalingstatechange = function () {
            console.log("onsignalingstatechange: " + pc.signalingState);
        }

        pc.onicecandidate = async function (event) {
            if (event.candidate) {
                console.log('new-ice-candidate:');
                console.log(event.candidate.candidate);
                console.log(event.candidate);
                await fetch(setIceCandidateUrl, {
                    method: 'POST',
                    body: JSON.stringify(event.candidate),
                    headers: { 'Content-Type': 'application/json' }
                });
            }
        };

        let offerResponse = await fetch(getOfferUrl);
        let offer = await offerResponse.json();
        console.log("got offer: " + offer.type + " " + offer.sdp + ".");
        await pc.setRemoteDescription(offer);

        pc.createAnswer().then(function (answer) {
            return pc.setLocalDescription(answer);
        }).then(async function () {
            console.log("Sending answer SDP.");
            console.log("SDP: " + pc.localDescription.sdp);
            await fetch(setAnswerUrl, {
                method: 'POST',
                body: JSON.stringify(pc.localDescription),
                headers: { 'Content-Type': 'application/json' }
            });
        });

    };

    function closePeer() {
        if (pc != null) {
            console.log("close peer");
            pc.close();
        }
    };

</script>

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>WebRTC ASP.Net Example with the <a target="_blank" href="https://github.com/sipsorcery/sipsorcery">SIPSorcery WebRTC Library</a>.</p>
</div>


<audio controls autoplay="autoplay" id="audioCtl"></audio>

<div>
    <button type="button" class="btn btn-success" onclick="start();">Start</button>
    <button type="button" class="btn btn-success" onclick="closePeer();">Close</button>
</div>
